<template>
    <div class="login">
        <mt-header fixed title="道路货物运输量专项调查" style="z-index: 999999;">
        </mt-header>
        <div id="progressbar1" class="mui-progressbar mui-progressbar-danger mui-hidden">
				<span></span>
			</div>
        <img class="userImg" src="../../images/logo.png"/>
        <div style="text-align: center;">
            道路货运调查-正式版
        </div>
        
        <div class="mui-input-row" style="width:90%">
            <label><img class="userNameImg" src="../../images/phone.png"></label>
            <input type="text" placeholder="输入用户名" v-model="userName" style="width:60%">
        </div>
        <hr>
        <div class="mui-input-row" style="width:90%">
            <label><img class="passwordImg" src="../../images/lock.png"></label>
            <input type="password" placeholder="输入密码" v-model="userPassword" class="mui-input-password" style="width:50%">
        </div>
        <hr>
        <div class="mui-input-row yzm" style="width:100%">
            <label><img class="keyImg" src="../../images/key.png"></label>
            <input type="text" placeholder="输入验证码" v-model="userKey">
            <div class="check" @click="refreshCode">
                <SIdentify :identifyCode="identifyCode"></SIdentify>
            </div>
        </div>
        <hr class="last">
        <div class="mui-button-row">
            <mt-button class="loginbuttom" size="normal" type="primary" @click="login">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;登录&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</mt-button>
            <!-- <mt-button class="forgetbuttom" size="normal" type="primary" @click="forgetpassword">&nbsp;忘记密码&nbsp;
            </mt-button> -->
        </div>
        <div class="link-area">
            <a id="forgetPassword" @click="forgetpassword">忘记密码</a>
            <span class="spliter">|</span>            
            <a id="reg" @click="register">司机注册</a>
        </div>
    </div>
</template>

<script>
    //导入验证码
    import SIdentify from '../../components/toolsContainer/identity.vue'
    import {Toast} from 'mint-ui'
    import CryptoJS from 'crypto-js'
    import mui from '../../lib/mui/js/mui.min.js'

    export default {
        data() {
            return {
                userName: '',
                userPassword: '',
                userKey: '',
                identifyCode: "",
                verificationCodeId: '',
                sessionId: '',
                errormsg: '',
            }
        },
        created() {
           
        },
        mounted() {
            
            this.identifyCode = "";
            this.makeCode();
            this.saveState();
            
        },
        methods: {
            //司机注册
            register(){
                this.$router.push({ path: "/login/register" });
            },
            saveState(){
                localStorage.setItem("loginFlag",false);
                console.log(localStorage.getItem("loginFlag"));
            },
            login() {
                var passWord = this.set(this.userPassword, 'CYDCxtaesmy2046j');
                if (this.userName === null || this.userName === '') {
                    Toast("用户名不能为空");
                    return;
                }
                if (this.userPassword === null || this.userPassword === '') {
                    Toast("密码不能为空");
                    return;
                }
                if (this.identifyCode != this.userKey) {
                    Toast("验证码不正确");
                    return;
                }
                this.axios.post('http://zxdc.catsic.com:9090/sampling/user/login', {
                    'data': {
                        "name": this.userName,
                        "password": passWord,
                        "verificationCode": this.userKey,
                        "verificationCodeId": this.verificationCodeId
                    }
                }, {
                    'headers': {
                        'Content-Type': 'application/json',
                        'mobileHeader': '{"sessionId":""}'
                    }
                }).then(result => {
                    console.log(result);
                    if (result.data.status == "1000") {
                        localStorage.setItem("loginFlag",true);
                        this.sessionId = result.data.data.sessionId;
                        localStorage.setItem("userName",this.userName);
                        localStorage.setItem('sessionId', JSON.stringify(this.sessionId));
                        localStorage.setItem('UserRole',result.data.data.UserRole);
                        if(result.data.data.UserRole == "货车司机"){
                            localStorage.setItem('userInfo',JSON.stringify(result.data.data));                        
                            
                            if (result.data.data.phoneBinding == 0) {
                                this.$router.push({
                                path: "/login/withPhoneNumber"
                                });
                            } else {
                                this.$store.commit("changeLoginStatus");
                                this.$router.push({
                                path: "/FZBTableCheckSj"
                                });
                            }    
                        } else {
                            if (result.data.data.phoneBinding == 0) {
                                this.$router.push({
                                    path: '/login/withPhoneNumber'
                                });
                            } else {
                                this.$store.commit("changeLoginStatus");
                                this.$router.push({
                                    path: '/home'
                                });
                            }
                        }
                        
                    } else {
                        this.refreshCode();
                        this.msg = result.data.msg;
                        Toast(this.msg);
                        return;
                    }
                },error=>{
                    console.log(error);
                });
            },
            forgetpassword() {
                this.$router.push({path: '/login/forgetPassword'});
            },
            refreshCode() {
                this.identifyCode = "";
                this.makeCode();
                console.log('当前验证码是', this.identifyCode)
            },
            makeCode() {
                this.axios.post('http://zxdc.catsic.com:9090/sampling/code/getverificationcode',
                ).then(result => {
                    console.log(result.data.data);
                    if (result.data.status == "1000") {
                        //成功
                        this.identifyCode = result.data.data.verificationCode;
                        this.verificationCodeId = result.data.data.verificationCodeId;
                    } else {
                        Toast("验证码获取错误");
                    }
                    this.checkVersion();
                },error=>{
                    console.log(error);
                });
            },
            set(word, keyStr) {
                keyStr = keyStr ? keyStr : 'CYDCxtaesmy2046j';   //16位的密钥，自己定义，和下面的密钥要相同
                var key = CryptoJS.enc.Utf8.parse(keyStr);
                var srcs = CryptoJS.enc.Utf8.parse(word);
                var encrypted = CryptoJS.AES.encrypt(srcs, key, {mode: CryptoJS.mode.ECB, padding: CryptoJS.pad.Pkcs7});
                return encrypted.toString();
            },
            //解密
            get(word, keyStr) {
                keyStr = keyStr ? keyStr : 'CYDCxtaesmy2046j';
                var key = CryptoJS.enc.Utf8.parse(keyStr);
                var decrypt = CryptoJS.AES.decrypt(word, key, {mode: CryptoJS.mode.ECB, padding: CryptoJS.pad.Pkcs7});
                return CryptoJS.enc.Utf8.stringify(decrypt).toString();
            },
            checkVersion(){
                let version = "1.2";
               // if(mui.os.android){
					//获取当前版本号,并检测新版本
					// plus.runtime.getProperty(plus.runtime.appid, function(inf) {
					// 	version = inf.version; //当前版本数字
						
					// });
				
                this.axios
                    .post(
                    //"http://zxdc.catsic.com:9090/sampling/appVersionCheck/checkVersion",
                    "http://zxdc.catsic.com:9090/sampling/appVersionCheck/checkVersionForOfficial",
                    {
                        data: {
                        version: version,                       
                        }
                    },
                    {
                        headers: {
                        "Content-Type": "application/json",
                        mobileHeader:
                            '{"sessionId":' + localStorage.getItem("sessionId") + "}"
                        }
                    }
                    )
                    .then(result => {
                        if (result.data.status === "1000") {
                            console.log("版本更新获取数据:"+JSON.stringify(result));
                            if(result.data.data.MSG == "1"){
                                this.updatedVersion(result.data.data.appVersion.apkurl,result.data.data.appVersion.version);
                            }
                        } else {
                            
                        }
                    });
               // }
            },
            
            updatedVersion(URL,v){
                this.apkurl = URL;
                var btnArray = ['确定', '取消'];
                    mui.confirm("有新版本("+v+"),是否更新", "", btnArray, function(e) {
                        if(e.index == 0) {
                            plus.nativeUI.toast("开始下载...");
                            console.log("下载地址："+URL);
                            //这里是开始显示进度条
                            mui("#progressbar1")[0].classList.remove("mui-hidden");
                            mui("#progressbar1").progressbar({
                                progress: 0
                            }).show();
                            var dtask = plus.downloader.createDownload(URL, {}, function(download, status) {
                                if(download.state == 4 && status == 200) {
                                    plus.nativeUI.toast("下载完毕，开始安装");
                                    var path = download.filename; //下载apk
                                    plus.runtime.install(path); // 自动安装apk文件
                                    plus.nativeUI.alert("更新完成！", function() {
                                        //  更新完成后重启应用
                                       plus.runtime.restart();
                                    });
                                } else {
                                    alert('版本更新失败:' + status);
                                    mui("#progressbar1")[0].classList.add("mui-hidden");
                                }
                            });
                            dtask.addEventListener("statechanged", onStateChanged, false);
                            dtask.start();
                            //监听器，用来显示实时显示下载信息 
                            function onStateChanged(download, status) {
                                if(download.state == 3) {
                                    var totalSize = dtask.totalSize;
                                    var downloadedSize = dtask.downloadedSize;
                                    mui("#progressbar1").progressbar().setProgress((downloadedSize / totalSize) * 100);
                                    //	下载完成隐藏进度条
                                    if(downloadedSize != 0 && downloadedSize >= totalSize) {
                                        mui("#progressbar1")[0].classList.add("mui-hidden");
                                    }
                                }
                            }
                        }
                    })
            },
        },
        components: {
            //引入子组件
            "SIdentify": SIdentify,
        },
    }


</script>

<style lang="scss" scoped>
    label {
        padding: 0 0 0 0;
    }

    hr {
        margin-top: 0;
        margin-right: 15%;
        float: right;
        width: 58%;
    }

    .last {
        margin-top: 0;
        margin-right: 37%;
        float: right;
        width: 36%;
    }

    .userNameImg {
        width: 40%;
        margin-left: 40%;
        margin-top: 15%;
    }

    .passwordImg {
        width: 40%;
        margin-left: 40%;
        margin-top: 15%;
    }

    .keyImg {
        width: 40%;
        margin-left: 40%;
        margin-top: 15%;
    }

    .userImg {
        padding-left: 40%;
        padding-top: 18%;
        width: 59%;
        height: 100%;
    }

    .mui-input-group {
        margin-top: 10%;
        background-color: #efeff4;
    }

    .mui-input-group {
        position: unset
    }

    .mui-input-group .mui-input-row {
        height: 70px;
    }

    .loginbuttom {
        margin-top: 15%;
        
        width: 60%
    }

    .forgetbuttom {
        margin-top: 15%;
    }

    .mui-input-row label ~ input, .mui-input-row label ~ select, .mui-input-row label ~ textarea {
        float: left;
        width: 35%;
        padding-top: 10%;
    }

    // .mui-input-row .mui-input-clear ~ .mui-icon-clear, .mui-input-row  .mui-input-row .mui-input-speech ~ .mui-icon-speech {
    //     font-size: 20px;
    //     position: unset;
    //     z-index: 1;
    //     top: 70%;
    //     right: 0;
    //     width: 38px;
    //     height: 38px;
    //     text-align: center;
    //     color: #fff;
    // }

    .mui-icon-eye{
        margin-right: 10%;
    }

    .mui-input-row label {
        width: 30%
    }

    .check {
        margin-top: 3%;
        padding-right: 3%;
        width: 33%;
        height: 40px;
        float: right;
    }

    .mui-input-row input {
        width: 65%;
    }

    // .mui-input-row {
    //     position: unset;
    // }

    .mui-input-row {
        // position: unset;
          margin-top: 10%;
        //  margin-right: 12%;
         
    }

    .link-area {
        display: block;
        margin-top: 25px;
        text-align: center;
    }
    .link-area a {
        color: #26A2FF;
    }
    .spliter {
        color: #bbb;
        padding: 0px 8px;
    }
</style>